var mysql = require('mysql');
var config = require('../../webconfig.js');

module.exports = function () {
    var formatFun = function (query, values) {
        if (!values || values.length == 0) return query;
        var v = values;
        if (values instanceof Array) {
            for (var i = 0; i < values.length; i++) {
                if (values[i] && values[i].constructor == Object) {
                    //v = values.pop();
                    v = values[i];
                    break;
                }
            }
        }
        query = mysql.format(query, values);
        return query.replace(/\:(\w+)/g, function (txt, key) {
            if (isNaN(key)&&v.hasOwnProperty(key)) {
                return this.escape(v[key]);
            }
            return txt;
        }.bind(this))
    };

    config.dataSource.dev.queryFormat = formatFun;
    config.dataSource.test.queryFormat = formatFun;
    config.dataSource.prod.queryFormat = formatFun;

    return {
        dev: config.dataSource.dev,
        test: config.dataSource.test,
        prod: config.dataSource.prod
    };
}();
